package com.vito.util.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

public class OSSUtil {

	final static Logger log = LoggerFactory.getLogger(OSSUtil.class);

    public static boolean uploadFile(String endpoint, String accessKey, String accessSecret, String bucketName, String objectName, String contentType, String fileFullName, String downloadFileName) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(fileFullName));
            return uploadFile(endpoint, accessKey, accessSecret, bucketName, objectName, contentType, inputStream, downloadFileName);
        } catch (Exception e) {
            return false;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e1) {
                }
            }
        }
    }

    public static boolean uploadFile(String endpoint, String accessKey, String accessSecret, String bucketName, String objectName, String contentType, InputStream inputStream) {
        return uploadFile(endpoint, accessKey, accessSecret, bucketName, objectName, contentType, inputStream, null);
    }

    public static boolean uploadFile(String endpoint, String accessKey, String accessSecret, String bucketName, String objectName, String contentType, InputStream inputStream, String downloadFileName) {

        OSSClient ossClient = new OSSClient(endpoint, accessKey, accessSecret);

        ObjectMetadata meta = new ObjectMetadata();
        if (contentType != null) {
            meta.setContentType(contentType);
        }

        if (!StringUtils.isEmpty(downloadFileName)) {
            meta.setContentDisposition("attachment; filename=\"" + downloadFileName + "\"");
        }

        try {
            ossClient.putObject(bucketName, objectName, inputStream, meta);
        } catch (Exception e) {
        	log.error(e.getMessage());
            return false;
        } finally {
            ossClient.shutdown();
        }
        return true;
    }

    public static String getSignedUrl(String endpoint, String accessKey, String accessSecret, String bucketName, String objectName, Date expiration) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKey, accessSecret);

        try {
            URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
            return url.toString();
        } catch (Exception e) {
            return null;
        } finally {
            ossClient.shutdown();
        }
    }
}
